package org.example.顺序消息.消费;

import lombok.SneakyThrows;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.*;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

/**
 * @Auther:Liu
 * @Testname:顺序消息消费
 * @Date:2025/8/22 16:43
 */
public class 顺序消息消费 {
    @SneakyThrows
    public static void main(String[] args) {
        // 1.创建消费者 Consumer，指定消费者组名
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("producer_group_a");
        // 2.指定 NameSrv 地址
        consumer.setNamesrvAddr("192.168.10.88:9876");
        // 3.设定消费模式 （默认广播）
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
        // 4.订阅主题 Topic 和 Tag
        consumer.subscribe("topic_a", "global");
        // 5.设置回调函数，处理消息
        consumer.registerMessageListener(new MessageListenerOrderly() {
            @Override
            public ConsumeOrderlyStatus consumeMessage(List<MessageExt> list, ConsumeOrderlyContext consumeOrderlyContext) {
                try {
                    for (MessageExt msg : list) {
                        System.out.println(new String(msg.getBody()));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    return ConsumeOrderlyStatus.SUSPEND_CURRENT_QUEUE_A_MOMENT;
                }
                return ConsumeOrderlyStatus.SUCCESS;
            }
        });
        // 6.启动消费者 Consumer
        consumer.start();
    }
}

